﻿using System;
using System.Threading.Tasks;
using Pay.Core;
using Pay.DTO.chpay;
using Flurl.Http;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Linq;

namespace Pay.Service {
	public class ChPaySign {
		public ChPaySign() {
		}
#if DEBUG
		protected string api_url = "http://openapitest.tf56.com/service/api";
		public const string key = "08Oe4YI71I5S3e72qYT2";
		public const string appid = "2013001";
		public const string accountnumber = "8801111111377";
		public const string enterprisecode = "";
		public const string ak = "";
#else
		protected string api_url = "http://openapi.tf56.com/service/api";
		public const string key = "fff87b8f215a7b38d46f";
		public const string appid = "1392001";
		public const string accountnumber = "8800009882641";
		public const string enterprisecode = "6688150135020955";
		public const string ak = "Q08Ow5Y81WB6x2b8";
#endif

		#region 代付
		/// <summary>
		/// 请求
		/// </summary>
		/// <returns>The gateway.</returns>
		/// <param name="model">Model.</param>
		/// <typeparam name="T">The 1st type parameter.</typeparam>
		public async Task<ch_base_resp<T>> PayGateway<T>(ch_base_req model) {
			model.appid = appid;
			//if (model.service_id != "tf56pay.enterprise.queryEnterpriseAccountBanlance")
			//	model.service_id = model.service_id.Replace("tf56pay", "tf56enterprise");
			var log = IocHelper.Get<ILogHelper>("info");
			model.tf_sign = SecureHelper.MD5(_sign(model)).ToUpper();
			var json = model.ToJson();
			log.Info(json);
			try {
				var resp1 = await api_url.PostUrlEncodedAsync(model).ReceiveString();
				log.Info(resp1);
				return resp1.ToObject<ch_base_resp<T>>();
				//var resp = await api_url.PostJsonAsync(model).ReceiveJson<T>();
				//log.Info(resp.ToJson());
				//return resp;
			} catch (FlurlHttpException ex) {
				log.Error(ex.Message);
				return null;
			}
		}

		/// <summary>
		/// 签名
		/// </summary>
		/// <returns>The sign.</returns>
		/// <param name="model">Model.</param>
		private string _sign(ch_base_req model) {
			string json = model.ToJson();
			var collection = json.ToObject<SortedDictionary<string, object>>();
			collection.Remove("tf_sign");
			collection.Add("dog_sk", key);
			var dc = new Dictionary<string, object>();
			foreach (var item in collection.Reverse()) {
				dc.Add(item.Key, item.Value);
			}
			string result = string.Empty;
			foreach (var kv in dc) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString()))
					result += kv.Value;
			}
			//result = result.Trim('&');
			//result += "&dog_sk=" + key;
			var log = IocHelper.Get<ILogHelper>("info");
			log.Info(result);
			return result;
		}

		//public async Task<string> DownLoad(cn_tip_req model) {
		//	model.appid = appid;
		//	//if (model.service_id != "tf56pay.enterprise.queryEnterpriseAccountBanlance")
		//	//	model.service_id = model.service_id.Replace("tf56pay", "tf56enterprise");
		//	var log = IocHelper.Get<ILogHelper>("info");
		//	var collection = model.ToJson().ToObject<SortedDictionary<string, object>>();
		//	collection.Remove("tf_sign");
		//	collection.Add("dog_sk", key);
		//	var dc = new Dictionary<string, object>();
		//	foreach (var item in collection.Reverse()) {
		//		dc.Add(item.Key, item.Value);
		//	}
		//	string query = string.Empty;
		//	string result = string.Empty;
		//	foreach (var kv in dc) {
		//		if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString())) {
		//			result += kv.Value;
		//			query += string.Format("&{0}={1}", kv.Key, kv.Value);
		//		}
		//	}
		//	log.Info(result);
		//	model.tf_sign = SecureHelper.MD5(result).ToUpper();
		//	var json = model.ToJson();
		//	log.Info(json);
		//	query += string.Format("&{0}={1}", "tf_sign", model.tf_sign);
		//	query = "?" + query.Trim('&');
		//	try {
		//		var path = IOHelper.GetMapPath("chpay", model.statementdate);
		//		var url = api_url + query;
		//		log.Info(url);
		//		var fileName = await url.DownloadFileAsync(path, model.statementdate + ".zip");
		//		//ZipHelper.UnZip(fileName, path);
		//		log.Info(fileName);
		//		return string.Format("{0}_{1}_T_{1}.csv", enterprisecode, accountnumber, model.statementdate);
		//	} catch (FlurlHttpException ex) {
		//		log.Error(ex.Message);
		//		return null;
		//	}
		//}

		/// <summary>
		/// 异步通知验签
		/// </summary>
		/// <param name="model">Model.</param>
		public bool VerifySign(ch_transfer_notify model) {
			var log = IocHelper.Get<ILogHelper>("info");
			string singstr = model.ToJson();
			log.Info(singstr);
			var collection = model.ToJson().ToObject<SortedDictionary<string, object>>();
			var sign = model.tf_sign;
			collection.Remove("tf_sign");
			collection.Add("dog_sk", key);
			var dc = new Dictionary<string, object>();
			foreach (var item in collection.Reverse()) {
				dc.Add(item.Key, item.Value);
			}
			string result = string.Empty;
			foreach (var kv in dc) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString())) {
					if (kv.Key == "transactionamount") {
						result += model.transactionamount.ToString("0.00");
					} else if (kv.Key == "billamount") {
						result += model.billamount.Value.ToString("0.00");
					} else
						result += kv.Value;
				}
			}
			//result = result.Trim('&');
			//result += "&dog_sk=" + key;
			log.Info(result);
			result = SecureHelper.MD5(result).ToUpper();
			log.Info(result);
#if DEBUG
            result = sign = "";
#endif
            return result == sign;
		}

		/// <summary>
		/// 批量异步通知验签
		/// </summary>
		/// <param name="model">Model.</param>
		public bool VerifySign(cn_transferbatch_notify model) {
			var log = IocHelper.Get<ILogHelper>("info");
			string singstr = model.ToJson();
			log.Info(singstr);
			var collection = singstr.ToObject<SortedDictionary<string, object>>();
			var sign = model.tf_sign;
			collection.Remove("tf_sign");
			collection.Add("dog_sk", key);
			var dc = new Dictionary<string, object>();
			foreach (var item in collection.Reverse()) {
				dc.Add(item.Key, item.Value);
			}
			string result = string.Empty;
			foreach (var kv in dc) {
				if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString())) {
					result += kv.Value;
				}
			}
			//result = result.Trim('&');
			//result += "&dog_sk=" + key;
			log.Info(result);
			result = SecureHelper.MD5(result).ToUpper();
			log.Info(result);
			return result == sign;
		}
		#endregion

		#region 扫码
		#endregion
	}
}
